"""Configuration settings for the CLU API service using Pydantic Settings."""

import json
import sys
from pathlib import Path
from typing import List, Optional

from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict

from exceptions import InvalidConfigError
from models import ProjectDeploymentPair


class Settings(BaseSettings):
    """
    应用程序配置设置。
    
    支持多种配置来源（按优先级排序）：
    1. 环境变量
    2. config.json 文件
    3. 默认值
    """
    
    # API Configuration
    key: str = Field(..., description="Azure CLU API密钥")
    endpoint: str = Field(..., description="Azure CLU API端点")
    default_targets: List[ProjectDeploymentPair] = Field(
        default_factory=list, 
        description="默认的项目/部署对列表（已弃用，现从CosmosDB获取）",
        alias="DEFAULT_TARGETS"
    )
    
    # CORS Configuration
    cors_origins: List[str] = Field(
        default=[
            "http://localhost:8000",
        ],
        description="允许的CORS源列表",
        alias="CORS_ORIGINS"
    )
    
    # Server Configuration
    host: str = Field(default="0.0.0.0", description="服务器主机地址", alias="HOST")
    port: int = Field(default=8055, description="服务器端口", alias="PORT")
    reload: bool = Field(default=True, description="是否启用热重载", alias="RELOAD")
    
    # Default Language Setting
    default_language: str = Field(default="zh", description="默认语言", alias="DEFAULT_LANGUAGE")
    
    # Log Configuration
    log_level: str = Field(default="INFO", description="日志级别", alias="LOG_LEVEL")
    log_retention_days: int = Field(default=30, description="日志保留天数", alias="LOG_RETENTION_DAYS")
    log_timezone: str = Field(default="Asia/Shanghai", description="日志时区", alias="LOG_TIMEZONE")
    
    # CosmosDB Configuration
    cosmos_account_endpoint: str = Field(..., description="CosmosDB账户端点", alias="COSMOS_ACCOUNT_ENDPOINT")
    cosmos_account_key: str = Field(..., description="CosmosDB账户密钥", alias="COSMOS_ACCOUNT_KEY")
    cosmos_database_name: str = Field(default="novonordisk", description="CosmosDB数据库名称", alias="COSMOS_DATABASE_NAME")
    cosmos_container_name: str = Field(default="settings", description="CosmosDB容器名称", alias="COSMOS_CONTAINER_NAME")
    cosmos_connection_timeout: int = Field(default=5, description="CosmosDB连接超时时间（秒）", alias="COSMOS_CONNECTION_TIMEOUT")
    cosmos_query_timeout: int = Field(default=10, description="CosmosDB查询超时时间（秒）", alias="COSMOS_QUERY_TIMEOUT")
    
    # Startup Health Check Configuration
    startup_health_check_enabled: bool = Field(default=True, description="是否启用启动健康检查", alias="STARTUP_HEALTH_CHECK_ENABLED")
    startup_health_check_timeout: int = Field(default=15, description="启动健康检查超时时间（秒）", alias="STARTUP_HEALTH_CHECK_TIMEOUT")
    cosmos_health_check_required: bool = Field(default=True, description="是否要求CosmosDB健康检查通过才能启动", alias="COSMOS_HEALTH_CHECK_REQUIRED")
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        populate_by_name=True
    )
    
    
    @field_validator('key')
    @classmethod
    def validate_key(cls, v):
        """验证API密钥。"""
        if not v or not v.strip():
            raise ValueError("API密钥不能为空")
        return v.strip()
    
    @field_validator('endpoint')
    @classmethod
    def validate_endpoint(cls, v):
        """验证API端点。"""
        if not v or not v.strip():
            raise ValueError("API端点不能为空")
        if not v.startswith(('http://', 'https://')):
            raise ValueError("API端点必须是有效的URL")
        return v.strip().rstrip('/')
    
    
    @field_validator('port')
    @classmethod
    def validate_port(cls, v):
        """验证端口号。"""
        if not (1 <= v <= 65535):
            raise ValueError("端口号必须在1-65535之间")
        return v
    
    @field_validator('log_level')
    @classmethod
    def validate_log_level(cls, v):
        """验证日志级别。"""
        valid_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
        if v.upper() not in valid_levels:
            raise ValueError(f"日志级别必须是以下之一：{', '.join(valid_levels)}")
        return v.upper()
    
    @field_validator('cosmos_account_endpoint')
    @classmethod
    def validate_cosmos_endpoint(cls, v):
        """验证CosmosDB端点。"""
        if not v or not v.strip():
            raise ValueError("CosmosDB端点不能为空")
        if not v.startswith('https://'):
            raise ValueError("CosmosDB端点必须使用HTTPS协议")
        return v.strip().rstrip('/')
    
    @field_validator('cosmos_account_key')
    @classmethod
    def validate_cosmos_key(cls, v):
        """验证CosmosDB密钥。"""
        if not v or not v.strip():
            raise ValueError("CosmosDB密钥不能为空")
        return v.strip()
    
    def display_config_info(self) -> None:
        """显示配置加载信息。"""
        print(f"配置加载成功：endpoint={self.endpoint[:50]}...")
        print(f"项目配置现从CosmosDB动态获取")
        print(f"服务器将在 {self.host}:{self.port} 启动")
        print(f"启动健康检查：{'启用' if self.startup_health_check_enabled else '禁用'}")
        if self.startup_health_check_enabled:
            print(f"CosmosDB检查要求：{'严格模式' if self.cosmos_health_check_required else '宽松模式'}")
            print(f"健康检查超时：{self.startup_health_check_timeout}秒")


# 创建全局设置实例
try:
    settings = Settings()
    # 配置信息显示已移至 main.py 中的启动流程，避免重复打印
except Exception as e:
    print(f"配置加载失败：{e}", file=sys.stderr)
    sys.exit(1)
